﻿using FI.Core.IoC;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;



namespace Sample.Common.Mvc
{

    public abstract class BaseController<TDefaultBusinessComponent> : Controller
    {
        protected TDefaultBusinessComponent Service
        {
            get { return ServiceLocator.GetService<TDefaultBusinessComponent>(); }
        }
        public static readonly string BodyDivId = "BodyDiv";
        protected IServiceLocator ServiceLocator
        {
            get { return ServiceLocatorFactory.GetServiceLocator(); }
        }


        //本地路径转换成URL相对路径
        protected string UrlConvertor(string imagesUrl)
        {
            string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
            string imagesurl2 = imagesUrl.Replace(tmpRootDir, ""); //转换成相对路径
            imagesurl2 = imagesurl2.Replace(@"\", @"/");
            return imagesurl2;
        }


        //相对路径转换成服务器本地物理路径
        protected string UrlConvertorLocal(string imagesUrl)
        {
            string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
            string imagesurl2 = tmpRootDir + imagesUrl.Replace(@"/", @"\"); //转换成绝对路径
            return imagesurl2;
        }
         
    }


    public static class ModelStateHelper
    {
        public static IEnumerable<KeyValuePair<string, string[]>> Errors(this ModelStateDictionary modelState)
        {
            if (!modelState.IsValid)
            {
                return modelState.ToDictionary(kvp => kvp.Key,
                    kvp => kvp.Value.Errors
                                    .Select(e => e.ErrorMessage).ToArray())
                                    .Where(m => m.Value.Count() > 0);
            }
            return null;
        }
    }


}
